# frozen_string_literal: true

class VariableTypeService < ApplicationService
  class << self
    def parse(value, variable_type)
      case variable_type.klass
      when String.name
        value.to_s
      when Integer.name
        value.to_i
      when Float.name
        value.to_f
      when Array.name, Hash.name, JSON.name
        JSON.parse value
      when 'Custom::Boolean'
        'true'.eql? value.to_s
      else
        value
      end
    end

    def create(params)
      type = VariableType.create! params.slice(:name, :klass)
      {
        code: 0,
        message: 'success',
        variable_type: type.as_json(type_to_json_fmt)
      }
    end

    def update(id, params)
      type = VariableType.find id
      type.update! params.slice(:name, :klass, :status)
      {
        code: 0,
        message: 'success',
        variable_type: type.as_json(type_to_json_fmt)
      }
    end

    def delete(id)
      VariableType.destroy(id)
      { code: 0, message: 'success' }
    end

    def search(params)
      types = VariableType.filter_status(params[:status])
        .filter_name(params[:name])
      total = types.count

      types = types.page_info(params[:page_size], params[:page_no])
        .includes(:type_methods)
        .as_json(type_to_json_fmt)
      {
        code: 0,
        message: 'success',
        total: total,
        variable_types: types
      }
    end

    def show(id)
      type = VariableType.find id
      {
        code: 0,
        message: 'success',
        variable_type: type.as_json(type_to_json_fmt)
      }
    end

    private

    def type_to_json_fmt
      {
        include: {
          type_methods: {
            only: %i[id name desciption parameters]
          }
        }
      }
    end
  end
end
